package com.service.impl;

import com.dao.SysRoleDao;
import com.dao.SysRoleMenuDao;
import com.dao.SysUserRoleDao;
import com.domain.PageObject;
import com.domain.sys.SysRole;
import com.domain.sys.SysRoleMenu;
import com.exception.ServiceException;
import com.service.SysRoleService;
import com.util.MyValid;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    private SysRoleDao sysRoleDao;

    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    @Autowired
    private SysUserRoleDao sysUserRoleDao;


    @Override
    public PageObject<SysRole> findPageObjects(String name, Integer pageCurrent) {
        MyValid.isIll(pageCurrent == null || pageCurrent < 1,"当前页码值无效");


        Integer row = sysRoleDao.getRowCount(name);

        MyValid.isService(row == 0,"没有找到对应记录");


        int indexSize = 10;
        ArrayList<SysRole> list = sysRoleDao.findPageObjects(name,(pageCurrent-1)*indexSize,indexSize);
        int pageCount  = row / indexSize;
        if(row % indexSize != 0)
            pageCount += 1;
        return new PageObject<SysRole>(pageCurrent,indexSize,row,pageCount,list);
    }

    @Override
    public Integer deleteObject(Integer id) {
        MyValid.isIll(id==null||id<=0,"请先选择");

        sysRoleMenuDao.deleteObjectsByRoleId(id);
        sysUserRoleDao.deleteObjectsByRoleId(id);

        int rows = sysRoleDao.deleteObject(id);
        MyValid.isService(rows == 0,"此记录可能不存在");
        return rows;
    }

    @Override
    public Integer saveObject(SysRole entity, Integer[] menuIds) {
        MyValid.isIll(entity == null,"保存对象不能为空");

        MyValid.isIll(StringUtils.isEmpty(entity.getName()),"角色名不能为空");

        MyValid.isService(menuIds==null||menuIds.length==0,"必须为角色分配权限");

        int rows = sysRoleDao.insertObjects(entity);

        sysRoleMenuDao.insertObjects(entity.getId(),menuIds);
        return rows;
    }

    @Override
    public SysRoleMenu findObjectById(Integer id) {
        MyValid.isIll(id == null || id <= 0,"id值不合法");

        SysRoleMenu result = sysRoleDao.findObjectById(id);
        MyValid.isService(result == null,"此记录已存在");
        return result;
    }

    @Override
    public Integer updateObject(SysRole entity, Integer[] menuIds) {

        MyValid.isIll(entity == null,"更新对象不能为空");

        MyValid.isIll(entity.getId() == null,"id值不能为空");

        MyValid.isIll(StringUtils.isEmpty(entity.getName()),"角色名不能为空");

        MyValid.isIll(menuIds == null || menuIds.length == 0,"请为角色指定一个权限");

        Integer row = sysRoleDao.updateObject(entity);
        MyValid.isService(row == 0,"数据已经消失啦");

        sysRoleMenuDao.deleteObjectsByRoleId(entity.getId());
        sysRoleMenuDao.insertObjects(entity.getId(),menuIds);
        return row;
    }


}
